package dmwr.web;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dmwr.util.Operation;

public final class Http {
	private static final ThreadLocal<HttpServletRequest> REQUEST = new ThreadLocal<HttpServletRequest>();
	private static final ThreadLocal<HttpServletResponse> RESPONSE = new ThreadLocal<HttpServletResponse>();

	private Http() {
	}

	public static HttpServletRequest request() {
		return REQUEST.get();
	}

	public static HttpServletResponse response() {
		return RESPONSE.get();
	}

	public static <T> T execute(Operation<T> op, HttpServletRequest request,
			HttpServletResponse response) {
		REQUEST.set(request);
		RESPONSE.set(response);
		try {
			return op.execute();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			REQUEST.set(null);
			RESPONSE.set(null);
		}
	}

	public static void forward(String path) {
		try {
			request().getRequestDispatcher("/WEB-INF/jsp" + path).forward(
					request(), response());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void redirect(String path) {
		try {
			response().sendRedirect(request().getContextPath() + path);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("rawtypes")
	public static String[] indexedParameter(String name) {
		List<String> list = new ArrayList<String>();
		for (Enumeration en = Http.request().getParameterNames(); en
				.hasMoreElements();) {
			String n = (String) en.nextElement();
			if (n.startsWith(name)) {
				int index = Integer.parseInt(n.substring(name.length()));
				while (index >= list.size()) {
					list.add(null);
				}
				list.set(index, Http.request().getParameter(n));
			}
		}
		return list.toArray(new String[list.size()]);
	}
}
